<?php
namespace Home\Org\Util;
class TTXApi{
    
    /**
     * 单例模式，实例化对象
     * 
     */
    public static $instance = NULL;
    public static $sqlObj = NULL;
  
    public static function instance() {
        if(self::$instance == NULL) {
            self::$instance = new self();
        }
        if(self::$sqlObj == NULL){
            import("@.ORG.Util.Sqlserver");
            self::$sqlObj  = new Sqlserver();
        }
        return self::$instance;
    }
    
    
    /**
     * 商品资料同步
     * @$num 第几条记录  从0开始
     */
    function itemrequest($num=0){
        $sql  = "SELECT top 1 * from (SELECT row_number () OVER (ORDER BY itemcode) AS rownumber, itemcode AS Item, '' BrandId, U_Brand AS Brand, ItemName AS ItemDesc, isnull(CodeBars, '') BarCode, isnull(U_size, '') GoodSpec, U_color Color, BLength1 Length, BWidth1 Width, BHeight1 Height, isnull(U_GW, '1.013') Weight, 'EA' Unit, '' Sprice, ManBtchNum ControlId, ManSerNum, ManBtchNum, isnull(U_Is3C, 'N3C') Is3c, '' UserDef1, '' UserDef2, '' UserDef3, '' UserDef4 FROM OITM ) A WHERE rownumber >{$num}";
        $data =  self::$sqlObj->query($sql);
        if(!$data[0])
        return false;
        unset($data[0]['rownumber']);
        if($data[0]['Is3c']=='非3C')$data[0]['Is3c']='N3C';
        return $data;
    }
    
    /**
     * 获取当天的物料 
     * @param number $num
     * @return boolean|string
     */
    function itemrequestByday($code){
        if(!$code)
            return false;
        $where = " where  itemcode='{$code}' ";
        $sql  = "SELECT row_number () OVER (ORDER BY itemcode) AS rownumber,CreateDate, itemcode AS Item, '' BrandId, U_Brand AS Brand, ItemName AS ItemDesc, isnull(CodeBars, '') BarCode, isnull(U_size, '') GoodSpec, U_color Color, BLength1 Length, BWidth1 Width, BHeight1 Height, isnull(U_GW, '1.013') Weight, 'EA' Unit, '' Sprice, ManBtchNum ControlId, ManSerNum, ManBtchNum, isnull(U_Is3C, 'N3C') Is3c, '' UserDef1, '' UserDef2, '' UserDef3, '' UserDef4 FROM OITM  ".$where;
        $data =  self::$sqlObj->query($sql);
        if(!$data[0])
            return false;
        unset($data[0]['rownumber']);
        if($data[0]['Is3c']=='非3C')$data[0]['Is3c']='N3C';
        return $data;
    }
    
    /**
     * sap触发式 查询采购入库单
     */
    function getreceiptrequestPOBysap($id){
        $sql = "SELECT 'GiftTown' company, 'HYWCK' warehouse, [dbo].[countdetail] ( docentry, 'por1', 'countqtys' ) totalqty, [dbo].[countdetail] ( docentry, 'por1', 'countlines' ) totallines, docentry docentry, docnum, objtype, docduedate, cardcode, cardname, comments, series FROM OPOR t1 WHERE t1.DocStatus = 'O' AND docentry IN ( SELECT docentry FROM por1 WHERE WhsCode IN ('HYWCK') ) AND docentry='{$id}'";
        return self::$sqlObj->query($sql);
    }
    
    
    /**
     * 采购入库单主单数据获取 一小时内单据
     */
     function getreceiptrequestPO(){
        $sql = "SELECT 'GiftTown' company, 'HYWCK' warehouse, [dbo].[countdetail] ( docentry, 'por1', 'countqtys' ) totalqty, [dbo].[countdetail] ( docentry, 'por1', 'countlines' ) totallines, docentry docentry, docnum, objtype, docduedate, cardcode, cardname, comments, series FROM OPOR t1 WHERE t1.DocStatus = 'O' AND docentry IN ( SELECT docentry FROM por1 WHERE WhsCode IN ('HYWCK') ) AND datediff( MINUTE, [dbo].[dateplustime] (createdate, doctime), GETDATE() ) <= 60";
        return self::$sqlObj->query($sql);
    }
    
    /**
     * 采购单物料数据
     * @param unknown $docnum
     */
     function receiptrequestItemsPO($docnum){
        $sql = "SELECT LineNum Polineid, ItemCode Item, Dscription ItemName , OpenQty ItemCount , PriceBefDi Sprice , '' Lot FROM POR1 t1 WHERE LineStatus='O' and WhsCode='HYWCK' and DocEntry ='{$docnum}'";
        return self::$sqlObj->query($sql);
    }
    
    /**
     * 销售退货库单主单数据获取 一小时内单据
     */
    function getreceiptrequestOR(){
        $sql = "select company,warehouse,sum(quantity) totalqty,count(quantity) totallines,docentry,docnum,objtype,docduedate,cardcode,cardname,comments from (select t1.DocEntry,'GiftTown'company,'HYWCK'warehouse,Quantity,DocNum,t1.ObjType,DocDueDate,CardCode,CardName,Comments, len = case when LEN(DocTime) = 4 then datediff(hh,dateadd(MINUTE,left(DocTime,2)*60+right(DocTime,2),CreateDate),GETDATE()) when len(DocTime) = 3 then datediff(hh,dateadd(MINUTE,left(DocTime,1)*60+right(DocTime,2),CreateDate),GETDATE()) when LEN(DocTime) = 2 or LEN(DocTime) = 1 then datediff(hh,dateadd(MINUTE,left(DocTime,0)*60+right(DocTime,2),CreateDate),GETDATE()) end from ORDN t1 left join RDN1 t2 on t1.DocEntry = t2.DocEntry) t3 where t3.len <= 1 group by company,warehouse,docnum,ObjType,docduedate,cardcode,cardname,comments,DocEntry order by docentry";
        return self::$sqlObj->query($sql);
    }
    
    /**
     *  销售退货库单物料
     * @param unknown $docnum
     */
    function receiptrequestItemsOR($docnum){
        $sql = "select LineNum Polineid,ItemCode Item,Dscription ItemName ,Quantity ItemCount,PriceBefDi Sprice , '' Lot from ORDN t1 left join RDN1 t2 on t1.DocEntry = t2.DocEntry where t2.DocEntry = (select docentry from(select top 1 t3.DocEntry,company,warehouse,sum(quantity) totalqty,count(quantity) totallines,docnum,ObjType,docduedate,cardcode,cardname,comments from (select t1.DocEntry,''company,''warehouse,Quantity,DocNum,t1.ObjType,DocDueDate,CardCode,CardName,Comments, len = case when LEN(DocTime) = 4 then datediff(hh,dateadd(MINUTE,left(DocTime,2)*60+right(DocTime,2),CreateDate),GETDATE()) when len(DocTime) = 3 then datediff(hh,dateadd(MINUTE,left(DocTime,1)*60+right(DocTime,2),CreateDate),GETDATE()) when LEN(DocTime) = 2 or LEN(DocTime) = 1 then datediff(hh,dateadd(MINUTE,left(DocTime,0)*60+right(DocTime,2),CreateDate),GETDATE()) end from ORDN t1 left join RDN1 t2 on t1.DocEntry = t2.DocEntry) t3 where t3.len <= 1 and docnum='{$docnum}' group by company,warehouse,docnum,ObjType,docduedate,cardcode,cardname,comments,DocEntry order by docentry) t4)";
        return self::$sqlObj->query($sql);
    }
    
    
    /**
     * 调拨入库单主单数据获取 一小时内单据
     */
    function getreceiptrequestGIN1(){
        $sql = "select company,warehouse,sum(quantity) totalqty,count(quantity) totallines,docentry,docnum,objtype,docduedate,cardcode,cardname,comments from (select t1.DocEntry,'GiftTown'company,'HYWCK'warehouse,Quantity,DocNum,t1.ObjType,DocDueDate,isnull(CardCode,'') cardcode,isnull(CardName,'') cardname,isnull(Comments,'') comments, len = case when LEN(DocTime) = 4 then datediff(hh,dateadd(MINUTE,left(DocTime,2)*60+right(DocTime,2),CreateDate),GETDATE()) when len(DocTime) = 3 then datediff(hh,dateadd(MINUTE,left(DocTime,1)*60+right(DocTime,2),CreateDate),GETDATE()) when LEN(DocTime) = 2 or LEN(DocTime) = 1 then datediff(hh,dateadd(MINUTE,left(DocTime,0)*60+right(DocTime,2),CreateDate),GETDATE()) end from OIGN t1 left join IGN1 t2 on t1.DocEntry = t2.DocEntry) t3 where t3.len <= 1 group by company,warehouse,docnum,ObjType,docduedate,cardcode,cardname,comments,DocEntry order by docentry";
        return self::$sqlObj->query($sql);
    }
    
    /**
     *  调拨入库单物料
     * @param unknown $docnum
     */
    function receiptrequestItemsGIN1($docnum){
        $sql = "select LineNum Polineid,ItemCode Item,Dscription ItemName ,Quantity ItemCount ,PriceBefDi Sprice from OIGN t1 left join IGN1 t2 on t1.DocEntry = t2.DocEntry where t2.DocEntry = (select docentry from(select top 1 t3.DocEntry,company,warehouse,sum(quantity) totalqty,count(quantity) totallines,docnum,ObjType,docduedate,cardcode,cardname,comments from (select t1.DocEntry,''company,''warehouse,Quantity,DocNum,t1.ObjType,DocDueDate,isnull(CardCode,'') cardcode,isnull(CardName,'') cardname,isnull(Comments,'') comments, len = case when LEN(DocTime) = 4 then datediff(hh,dateadd(MINUTE,left(DocTime,2)*60+right(DocTime,2),CreateDate),GETDATE()) when len(DocTime) = 3 then datediff(hh,dateadd(MINUTE,left(DocTime,1)*60+right(DocTime,2),CreateDate),GETDATE()) when LEN(DocTime) = 2 or LEN(DocTime) = 1 then datediff(hh,dateadd(MINUTE,left(DocTime,0)*60+right(DocTime,2),CreateDate),GETDATE()) end from OIGN t1 left join IGN1 t2 on t1.DocEntry = t2.DocEntry) t3 where t3.len <= 1 and docnum='{$docnum}' group by company,warehouse,docnum,ObjType,docduedate,cardcode,cardname,comments,DocEntry order by docentry) t4)";
        return self::$sqlObj->query($sql);
    }
    
    /**
     * 获取指定时间内的出库单 
     * $m 分钟
     */
    function getshipmentrequest($m=5){
        $sql = "SELECT t2.U_CardCode, 'HYW' company, 'HYWCK' warehouse, [dbo].[countdetail](U_OrderId,'ti_z0081','countqtys') totalqty, [dbo].[countdetail](U_OrderId,'ti_z0081','countlines') totallines, u_orderid ShipmentId,u_orderid, '' EbillNumber, '' BigChar, '线上订单' shipmenttype, [dbo].[expressRouter] ( U_OrderId, t2.U_CardCode,U_State,U_Address ) U_ExpCom, u_cstname, u_zipcode, '' phone, u_phone, dbo.[addressrouter](u_state,U_Address) u_state, u_city, u_county, u_address, t1.U_DocDate, '' cod, '' codvalue, '' u_deltimeq, isnull(t1.U_Memo, '') u_memo, '' checkdate, user_def1 = CASE WHEN u_inhead IS NOT NULL OR u_inhead <> 'null' THEN 'Y' ELSE 'N' END, CAST (t1.DocEntry AS nvarchar) + '~~' + CAST (Lineid AS nvarchar) user_def2, '' user_def3, '' user_def4 FROM [@ti_z0081] t1 LEFT JOIN [@TI_Z0080] t2 ON t1.DocEntry = t2.DocEntry where CAST (t1.DocEntry AS nvarchar) + '~~' + CAST (Lineid AS nvarchar) IN ( SELECT CAST (U_BsEntry AS nvarchar) + '~~' + CAST (U_BsLine AS nvarchar) FROM [@TI_Z0131] WHERE U_WhsCode = 'HYWCK' ) and U_OStatus='8' ORDER BY t1.DocEntry";
       // error_log($sql);
        return self::$sqlObj->query($sql);
        
    }
    
    /**
     * 根据id 获取出库单号 ,由sap触发 
     * @param unknown $id
     */
    function getshipmentrequestBySap($id){
        //$sql = "SELECT * from ( SELECT DISTINCT ISNULL(t1.U_Replace, '') U_Replace, t2.U_CardCode, 'HYW' company, 'HYWCK' warehouse, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countqtys' ) totalqty, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countlines' ) totallines, ( u_orderid + '~' + '{$id}' ) ShipmentId, u_orderid, '' EbillNumber, '' BigChar, '线上订单' shipmenttype, [dbo].[expressRouter] ( U_OrderId, t2.U_CardCode, U_State, U_Address ) U_ExpCom, u_cstname, u_zipcode, '' phone, u_phone, dbo.[addressrouter] (u_state, U_Address) u_state, u_city, u_county, u_address, t1.U_DocDate, '' cod, '' codvalue, '' u_deltimeq, isnull(t1.U_Memo, '') u_memo, '' checkdate, user_def1 = CASE WHEN u_inhead IS NOT NULL OR u_inhead <> 'null' THEN 'Y' ELSE 'N' END, '' user_def2, U_CardCode user_def3, '' user_def4 FROM [@ti_z0081] t1 LEFT JOIN [@TI_Z0080] t2 ON t1.DocEntry = t2.DocEntry WHERE CAST (t1.DocEntry AS nvarchar) + '~~' + CAST (Lineid AS nvarchar) IN ( SELECT CAST (U_BsEntry AS nvarchar) + '~~' + CAST (U_BsLine AS nvarchar) FROM [@TI_Z0131] WHERE U_WhsCode = 'HYWCK' AND DocEntry = '{$id}' ) AND U_OStatus = '8' ) a where a.U_Replace in ('','N')";
       // $sql =   "SELECT * from ( SELECT DISTINCT ISNULL(t1.U_Replace, '') U_Replace, t2.U_CardCode, 'HYW' company, 'HYWCK' warehouse, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countqtys' ) totalqty, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countlines' ) totallines, ( u_orderid + '~' + '{$id}' ) ShipmentId, u_orderid, '' EbillNumber, '' BigChar, '线上订单' shipmenttype, [dbo].[expressRouter] ( U_OrderId, t2.U_CardCode, U_State, U_Address ) U_ExpCom, u_cstname, u_zipcode, '' phone, u_phone, dbo.[addressrouter] (u_state, U_Address) u_state, u_city, u_county, u_address, t1.U_DocDate, '' cod, '' codvalue, '' u_deltimeq, isnull(t1.U_Memo, '') u_memo, '' checkdate, user_def1 = CASE WHEN u_inhead IS NOT NULL OR u_inhead <> 'null' THEN 'Y' ELSE 'N' END, '' user_def2, U_CardCode user_def3, dbo.AX_OrderDateTime(T1.u_docdate,T1.U_DocTime) user_def4 FROM [@ti_z0081] t1 LEFT JOIN [@TI_Z0080] t2 ON t1.DocEntry = t2.DocEntry WHERE CAST (t1.DocEntry AS nvarchar) + '~~' + CAST (Lineid AS nvarchar) IN ( SELECT CAST (U_BsEntry AS nvarchar) + '~~' + CAST (U_BsLine AS nvarchar) FROM [@TI_Z0131] WHERE U_WhsCode = 'HYWCK' AND DocEntry = '{$id}' ) AND U_OStatus = '8' ) a where a.U_Replace in ('','N')" ;
		$sql =   "SELECT * FROM ( SELECT DISTINCT ISNULL(t1.U_Replace, '') U_Replace, t2.U_CardCode, 'HYW' company, 'HYWCK' warehouse, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countqtys' ) totalqty, [dbo].[countdetail] ( U_OrderId, 'ti_z0081', 'countlines' ) totallines, ( u_orderid + '~' + '{$id}' ) ShipmentId, u_orderid, '' EbillNumber, '' BigChar, '线上订单' shipmenttype, [dbo].[expressRouter] ( U_OrderId, t2.U_CardCode, U_State, U_Address ) U_ExpCom, u_cstname, u_zipcode, '' phone, u_phone, dbo.[addressrouter] (u_state, U_Address) u_state, u_city, u_county, u_address, t1.U_DocDate, '' cod, '' codvalue, '' u_deltimeq, isnull(t1.U_Memo, '') u_memo, '' checkdate, user_def1 = CASE WHEN u_intype = '1' THEN 'Y' ELSE 'N' END, '' user_def2, U_CardCode user_def3, dbo.AX_OrderDateTime (T1.u_docdate, T1.U_DocTime) user_def4 FROM [@ti_z0081] t1 LEFT JOIN [@TI_Z0080] t2 ON t1.DocEntry = t2.DocEntry WHERE CAST (t1.DocEntry AS nvarchar) + '~~' + CAST (Lineid AS nvarchar) IN ( SELECT CAST (U_BsEntry AS nvarchar) + '~~' + CAST (U_BsLine AS nvarchar) FROM [@TI_Z0131] WHERE U_WhsCode = 'HYWCK' AND DocEntry = '{$id}' ) AND U_OStatus = '8' ) a WHERE a.U_Replace IN ('', 'N')";
		return self::$sqlObj->query($sql);
    
    }
    
    
    
    /**
     * 根据出库单订单号获取物料信息
     * @param unknown $orderId
     */
    function getshipmentrequestItem($orderId,$docentry){
        // InventorySts  SAP出库单 默认A08 可售库存状态
        $sql = "SELECT CAST (t1.DocEntry AS nvarchar(MAX)) + '-' + CAST (T1.LineId AS nvarchar(MAX)) Erporderlinenum, t0.U_ItemCode Item, t1.U_ItemName ItemName, t0.U_Qty ItemCount, t0.U_Price Sprice, '' Lot, 'A08' InventorySts FROM [@ti_z0131] T0 LEFT JOIN [@ti_z0081] T1 ON T0.U_BsEntry = T1.docentry AND T0.u_bsline = T1.lineid WHERE U_OrderId = '{$orderId}' AND T0.DocEntry = '{$docentry}' AND U_OStatus = '8' and T0.U_WhsCode='HYWCK' ";
       // error_log($sql);
       $data  = self::$sqlObj->query($sql);
       foreach ($data as $key=>$value){
           $data[$key]['Polineid'] = $key;
       }
        return $data;
    }
    
    /**
     * 特殊出库单
     */
    function teshushipmentrequest($id){
        $sql = "SELECT '' U_Replace, Cardcode U_CardCode, 'HYW' company, 'HYWCK' warehouse, [dbo].[countdetail] ( docentry, 'rdr1', 'countqtys' ) totalqty, [dbo].[countdetail] ( docentry, 'rdr1', 'countlines' ) totallines, ('TSCK~'+Convert(nvarchar(max),docentry)) ShipmentId, docnum u_orderid, '' EbillNumber, '' BigChar, 'TSCK' shipmenttype, '' U_ExpCom, '' u_cstname, '' u_zipcode, '' phone, '' u_phone, '' u_state, '' u_city, '' u_county, address u_address, t1.DocDate U_DocDate, '' cod, '' codvalue, '' u_deltimeq, '' u_memo, '' checkdate, '' user_def1, '' user_def2, '' user_def3, '' user_def4 FROM [ordr] t1 where docentry='{$id}' and cardcode='C30205'";
        return self::$sqlObj->query($sql);
    }
   
    /**
     * 特殊出库单物料详情
     * @param unknown $orderId
     * @param unknown $docentry
     * @return unknown
     */
    function getTeshushipmentrequestItem($docentry){
        $sql = "SELECT linenum Erporderlinenum, ItemCode Item, Dscription ItemName, Quantity ItemCount, Price Sprice, '' Lot, 'A08' InventorySts FROM rdr1 WHERE DocEntry = '{$docentry}' AND WhsCode = 'HYWCK'  and LineStatus='O' ";
        $data  = self::$sqlObj->query($sql);
        foreach ($data as $key=>$value){
            $data[$key]['Polineid'] = $key;
        }
        return $data;
    }
    
	
	 /**
     * 退货入(良品)库
     * @param unknown $id
     */
    function getreceiptrequestORBysap($id){
        $sql = "SELECT 'GiftTown' company, 'HYWCK' warehouse, [dbo].[countdetail] ( docentry, 'WTQ1', 'countqtys' ) totalqty, [dbo].[countdetail] ( docentry, 'WTQ1', 'countlines' ) totallines, docentry docentry, docnum, objtype, docduedate, cardcode, cardname, comments, 'OR' RECEIPT_TYPE, series FROM oWTQ t1 WHERE t1.DocStatus = 'O' AND docentry IN ( SELECT docentry FROM WTQ1 WHERE WhsCode IN ('HYWCK') ) AND docentry = '{$id}'";
        return self::$sqlObj->query($sql);
    }
    /**
     * 退货入良品库 物料数据
     * @param unknown $docnum
     */
    function receiptrequestItemsORNew($docnum){
        $sql = "SELECT LineNum Polineid, ItemCode Item, Dscription ItemName , OpenQty ItemCount , PriceBefDi Sprice , '' Lot FROM WTQ1 t1 WHERE LineStatus='O' and WhsCode='HYWCK' and DocEntry ='{$docnum}'";
        return self::$sqlObj->query($sql);
    }
	
	
	
    /**
     * 生成签名
     * @param unknown $sbubject
     * @param unknown $xml
     * @param string $from
     */
    static function getTTXSign($sbubject,$xml,$from='TTX'){
        $ckey ='0005de89463c4263a57630fe6c107e6a';
        $signArr = array();
        array_push($signArr, array('Message-From'=>$from));
        array_push($signArr, array('StRequest'   =>$xml));
        array_push($signArr, array('Subject'     =>$sbubject));
        // 按照key排序
        ksort($signArr);
        $tempSign = '';
        //所有key和value 拼接成字符串
        foreach ($signArr as $skey=>$va){
            if(key($va)&&$va[key($va)])
            $tempSign.=key($va).$va[key($va)];
        }
            $tempSign=$ckey.$tempSign.$ckey;
          // echo $tempSign;exit;
        return strtoupper(md5($tempSign));
    }
    
    /**
     * 入库单确认 ,生成文件后 执行DTW 导入sap系统
     * @param unknown $data
     */
    static function receiptconfim($data=array()){
        if(!$data||!is_array($data)){
            return  false;
        }
        $DocNum   = 1;
        $r_type = ''; //入库类型
        switch ($data['RECEIPT']['ReceiptType']){ //根据不同入库单  生成模板
            case 'PO':
                $r_type = 'PO'; //采购入库
                $modelConfig =  C('receiptconfim');
                $mtableName = 'think_receiptconfim_m';
                $stableName = 'think_receiptconfim_s';
                $m_model = M('ReceiptconfimM');
                $s_model = M('ReceiptconfimS');
                $baseType = '22';
                break;
                
            case 'OR': // 退货入库
                $r_type = 'OR';
                $m_model = M('TuihuoM');
                $s_model = M('TuihuoS');
                $mtableName = 'think_tuihuo_m';
                $stableName = 'think_tuihuo_s';
                $modelConfig =  C('tuihuo');
                $baseType = '12500000001';
                break;
                
            case 'GIN1': //调拨入库
                $r_type = 'GIN1';
                $m_model = M('DiaoboM');
                $s_model = M('DiaoboS');
                $mtableName = 'think_diaobo_m';
                $stableName = 'think_diaobo_s';
                $modelConfig =  C('diaobo');
                $baseType = '';
                break;
            default:
                return  false;
        }
       
        $ctime = time();
        if( $data['RECEIPT']['SHIP_FROM']=='S10763'){
            return true;
        }
        //主表数据
        $docDate     = date('Ymd',strtotime($data['RECEIPT']['ReceiptDate']));
        $data_ = $modelConfig['m'];//主数据模板
        $data_['DocNum']     = $DocNum;
        $data_['DocDate']    = $docDate;
        $data_['DocDueDate'] = $docDate;
        $data_['CardCode']   = $data['RECEIPT']['SHIP_FROM'];
        $data_['ctime']      = $ctime;
        $data_['U_FHLY']     = $data['RECEIPT']['ReceiptType'];
        $data_['Series']     = $data['RECEIPT']['Series'];
        $DocNum = $m_model->add($data_);
        $data_['DocNum'] = $DocNum;
        $m_model->where("U_wms_id={$DocNum}")->save($data_);
        $data_=$modelConfig['s']; //子数据模板
        $data_['ParentKey'] = $DocNum;
        
         //xml item如只有一个元素 默认会转成对象，此处将对象转成数组
        if(!count($data['RECEIPT']['Items']['Item'][0])){
            $data['RECEIPT']['Items']['Item']=array($data['RECEIPT']['Items']['Item']);
        } 
        $sqModel = M('ReceiptconfimSq');
        $items_have_ser =false; //所有物料中是否包含序列号商品,如不包含序列商品,需增加一行伪序列数据
        //数据重组
        $newData = array();
        foreach ($data['RECEIPT']['Items']['Item'] as $tempVO){
            if($newData){
                if( $newData[$tempVO['Item'].$tempVO['Polineid']]){
                    $newData[$tempVO['Item'].$tempVO['Polineid']]['ItemCount']+=$tempVO['ItemCount'];
                   /*  $newData[$tempVO['Item']]['Sprice']+=$tempVO['Sprice']; */
                    if($tempVO['ManSernum'])
                    $newData[$tempVO['Item'].$tempVO['Polineid']]['ManSernum'].='|-|'.$tempVO['ManSernum'];
                }else{
                    $newData[$tempVO['Item'].$tempVO['Polineid']] = $tempVO;
                }
                
            }else{
              $newData[$tempVO['Item'].$tempVO['Polineid']] = $tempVO;
            }
        }
        $saveData = array();
        foreach ($newData as $row){
            array_push($saveData, $row);
        }
        unset($newData);
        foreach ($saveData as $key=>$row){
            $data_['LineNum']       = $key;//$row['Polineid'];
            $data_['ItemCode']      = $row['Item'];
            $data_['WarehouseCode'] = $data['RECEIPT']['WareHouse'];
            $data_['Quantity']      = $row['ItemCount'];
            $data_['ItemDescription']      = $row['ItemName'];
			if(!$row['Sprice'])
				$row['Sprice']=0;
            $data_['LineTotal']     = $row['Sprice']*$row['ItemCount'];
            $data_['Price']     = $row['Sprice'];
            if($baseType){
                //只有采购入库 sap发起的单据才需要以下属性
            $tempId =explode('~', $data['RECEIPT']['ReceiptId']) ;
            $data_['BaseEntry']     = $tempId[0];
            $data_['BaseLine']      = $row['Polineid'];
            $data_['BaseType']      = $baseType; 
            }
            $data_['ctime']         = $ctime;
            $data_['AccountCode']   =  self::getShipmentType( $data['RECEIPT']['ReceiptType']);
            $s_model->add($data_);
            $manSernum = $row['ManSernum'];  //序列号
             if($manSernum){
                 $items_have_ser =true;
                 $sqModel->where("ParentKey={$DocNum} and InternalSerialNumber='' ")->delete();
                 $manSernumArr = explode('|-|', $manSernum);
                   foreach ($manSernumArr as $mkey=>$msr){
                     if($msr)
                    $sqModel->add(array('r_type'=>$r_type,'ParentKey'=>$DocNum,'LineNum'=>'','BaseLineNumber'=>$key,'InternalSerialNumber'=>$msr));
                 } 
            }
            if(!$items_have_ser){
                $sqModel->add(array('r_type'=>$r_type,'ParentKey'=>$DocNum));
                $items_have_ser =false;
                
            }
            
        }
       
        return true;
    }
    
    
    /**
     * 出库确认.
     * @param unknown $data
     * @return boolean
     */
     function shipmentConfim($data=array()){
        if(!$data||!is_array($data)){
            return  false;
        }
        $DocNum   = 1;
        switch ($data['SHIPMENT']['ShipmentType']){ //根据不同入库单  生成模板
            case '销售出库':
            case 'SO':
                $s_type = 'SO';
                $m_model = M('ShipmentXiaoshouM');
                $s_model = M('ShipmentXiaoshouS');
                $mtableName = 'think_shipment_xiaoshou_m';
                $stableName = 'think_shipment_xiaoshou_s';
                $modelConfig =  C('shipment_xiaoshou');
                //$project = '100002';
                $series = '61';
                break;
        
      /*       case '采购退货': //无此类型
            case 'OR':  
                $s_type = 'OR';
                $m_model = M('ShipmentCaigouM');
                $s_model = M('ShipmentCaigouS');
                $mtableName = 'think_shipment_caigou_m';
                $stableName = 'think_shipment_caigou_s';
                $modelConfig =  C('shipment_caigou');
                break;
                 */
               default: //其他类型默认为调拨模板
                $s_type = $data['SHIPMENT']['ShipmentType']; 
                $m_model = M('ShipmentDiaoboM');
                $s_model = M('ShipmentDiaoboS');
                $mtableName = 'think_shipment_diaobo_m';
                $stableName = 'think_shipment_diaobo_s';
                $modelConfig =  C('shipment_diaobo');
                $fhly   = self::getShipmentType($data['SHIPMENT']['ShipmentType']);
                $series = '';
                break;
        }
        $ctime = time();
        $docDate     = date('Ymd',strtotime($data['SHIPMENT']['ShipmentDate']));
        $data_ = $modelConfig['m'];//主数据模板
        $data_['DocNum']     = $DocNum;
        $data_['DocDate']    = $docDate;
        $data_['DocDueDate'] = $docDate;
        $data_['CardCode']   =$data['SHIPMENT']['SHIP_FROM'];
        //$data_['Project']    = @$project;
        $data_['Series']     = @$series;
        $data_['U_FHLY']     = @$fhly;
        $data_['ctime'] = $ctime;
        $DocNum = $m_model->add($data_);
        $data_['DocNum'] = $DocNum;
        $m_model->where("U_wms_id={$DocNum}")->save($data_);
        
        $data_=$modelConfig['s']; //子数据模板
        $data_['ParentKey'] = $DocNum;
        //xml item如只有一个元素 默认会转成对象，此处将对象转成数据
        $items_have_ser =false;
        $sqModel = M('ShipmentSq');
        if(!count($data['SHIPMENT']['Items']['Item'][0])){
            $data['SHIPMENT']['Items']['Item']=array( $data['SHIPMENT']['Items']['Item']);
        }
       
         $this->shipmenttoSapDB($data); //同步到sap数据库
        foreach ($data['SHIPMENT']['Items']['Item'] as $key=>$row){
            $data_['LineNum']       = $key;//$row['Polineid'];
            $data_['ItemCode']      = $row['Item'];
            $data_['ItemDescription']   = $row['ItemName'];
            $data_['AccountCode']   = @$fhly;
            $data_['WarehouseCode'] = $data['SHIPMENT']['WareHouse'];
            $data_['Price']         = $row['Sprice'];
            $data_['Width1']        =  (int)$data['SHIPMENT']['Weight'];
            $data_['ShipToCode']    = $row['Erporderlinenum'];
            $data_['Quantity']      = $row['ItemCount'];
            $data_['ctime']         = $ctime;
            if($data['SHIPMENT']['ShipmentType']=='SO'){ //如果是销售出库 FreeText 字段赋值(sap U_orderid)
            $data_['FreeText']      = $data['SHIPMENT']['ShipmentId'];
            if($data['SHIPMENT']['TrackingNumber']){
            $data_['ShipToDescription']  = $data['SHIPMENT']['Carrier'].'#'. $data['SHIPMENT']['TrackingNumber']; //快递单号 快递公司#单号 
            }
            }
            $s_model->add($data_);
            $manSernum = $row['ManSernum'];  //序列号
            if($manSernum){
                $items_have_ser = true;
                for($index=0;$index<$row['ItemCount'];$index++){
                    $systemSerialNumber = self::getSystemSerialNumberBySap($row['Item'], $manSernum);
                    $sqModel->add(array('s_type'=>$s_type,'ParentKey'=>$DocNum,'LineNum'=>$key, 'BaseLineNumber'=> $key,'InternalSerialNumber'=>$manSernum,'SystemSerialNumber'=>$systemSerialNumber));
                }
            }
             
        }
        if(!$items_have_ser){
            $sqModel->add(array('s_type'=>$s_type,'ParentKey'=>$DocNum));
            $items_have_ser =false;
        }
        return true;
        
    }
    
    /**
     * 从sqp获取物料的系统序列号
     * @param unknown $itemCode
     * @param unknown $seroal
     * @return unknown|boolean
     */
    static function getSystemSerialNumberBySap($itemCode,$seroal){
        $sql ="SELECT SysNumber from OSRN WHERE ItemCode='{$itemCode}' and DistNumber='{$seroal}'";
        $res = self::$sqlObj->query($sql)[0];
        if($res)
            return $res['SysNumber'];
        else 
            return false;
        
    }
    
    /**
     * 获取sap出库单类型
     * @param unknown $type
     * @return unknown
     */
    static function getShipmentType($type){
        import("@.ORG.Util.Sqlserver");
        $sql = "SELECT * from [@AX_INV_IN_OUT_TYPE] where Code='{$type}'";
        $sqlObj = new Sqlserver();
        $data = $sqlObj->query($sql);
        return $data[0]['U_acctCode'];
        
    }
    
    
    /**
     * 创建XML文件
     * @param string $root
     * @param unknown $atbArray
     * @param unknown $items
     * @param string $is_item 是否item为多个  默认为是
     * @return string
     */
    static function createXML($root='',$atbArray=array(),$items=array(),$is_item=true){
        $xml =  new \DOMDocument('1.0','UTF-8');
        $doc =  $xml->formatOutput = true;
        $root = $xml->createElement($root?:'root');
        $req  =  $xml->appendChild($root);
        foreach ($atbArray as $key=>$atb){
            $cmp =  $xml->createElement($key,$atb);
            $req  =  $root->appendChild($cmp);
        }
       
        if(count($items)){
        $itemsNode =  $xml->createElement('Items');
        foreach ($items as $vo){
            $node =   $xml->createElement('Item');
            $keys = array_keys($vo);
            foreach ($keys as $k){
                if(is_numeric($vo[$k])) $vo[$k]=ceil($vo[$k]);
                $node_temp =   $xml->createElement($k,htmlspecialchars($vo[$k]));
                if($is_item)
                $node->appendChild($node_temp);
                else 
                 $itemsNode->appendChild($node_temp);
            }
            if($is_item)
            $itemsNode->appendChild($node);
        }
        $root->appendChild($itemsNode);
        }
        
        return $xml->saveXML();
    }
    
    
    /**
     *
     * @param unknown $subject
     * @param unknown $from
     * @param unknown $xml
     * @param string  $url
     * @param string  $returnXML 是否返回xml格式 false返回数组
     * @return mixed|unknown
     */
    static function http($subject,$from,$xml,$sign='',$url='',$returnArr=true){
        if(!$url) $url='http://192.168.1.116:9090/INTERFACE/HYW_HttpListener.aspx';
        $header[]="Content-Type: text/xml; charset=utf-8";
        $header[]="Subject:{$subject}";
        $header[]="Message-From:{$from}";
        $header[]="SignKey:{$sign}";
        $header[]="Content-Length: ".strlen($xml);
       // error_log(var_export($header,1));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $res = curl_exec($ch);
        curl_close($ch);
        if($returnArr){
            return json_decode(json_encode((array) simplexml_load_string($res)), true);
        }
        return $res;
    }
    /**
     * 记录post  return 日志
     * @param unknown $fun
     * @param unknown $post
     * @param unknown $return
     * @return Ambigous <mixed, boolean, unknown, string>
     */
    static function log($fun,$post,$return){
            $logModel = M('WmsLog');
            return $logModel->add(
                array(
                    'post'=>$post,
                    'return'=>$return,
                    'ctime'=>date('Y-m-d H:i:s'),
                    'fun'=>$fun
                )    
            );
    }
    
    /**
     * sql 保存
     * @param unknown $model
     * @param unknown $data
     */
    static  function saveModeData($model,$data=array()){
         $arrkeys = array_keys($data);
         $sql ="insert into aaa ('".implode("`,`", $arrkeys).') values ('.implode("','", $data).')';
         return $model->query($sql);
        
        
    }
    
    /**
     * 修改单据状态  入库单
     * @param unknown $id
     * @param number $status
     */  
    static function UpdateBillStatus($model,$id,$status=1){
        $m = M($model);
        $smodel = substr($model, 0, strlen($model)-1).'S';
        $smodel = M($smodel);
        $smodel->where("ParentKey={$id}")->save(array('status'=>$status)); //字表记录状态
        //修改序列字表
        switch ($model){
            //采购入库
            case 'ReceiptconfimM':
                $sqModel = M('ReceiptconfimSq');
                $sqModel->where("ParentKey={$id} and r_type='PO' ")->save(array('status'=>$status));
                break;
                //调拨入库
           case 'DiaoboM':
                $sqModel = M('ReceiptconfimSq');
                $sqModel->where("ParentKey={$id} and r_type='GIN1' ")->save(array('status'=>$status));
               break;
               //销售退货入库
           case 'TuihuoM':
                $sqModel = M('ReceiptconfimSq');
                $sqModel->where("ParentKey={$id} and r_type='OR' ")->save(array('status'=>$status));
                break;               
               
          //采购退货出库      
          case 'ShipmentCaigouM':
                $sqModel = M('ShipmentSq');
                $sqModel->where("ParentKey={$id} and s_type='IGN' ")->save(array('status'=>$status));
                break;
                    
             //调拨类型出库       
          case 'ShipmentDiaoboM':
                $sqModel = M('ShipmentSq');
                $sqModel->where("ParentKey={$id} and s_type in ('GOUT1','GOUT10','GOUT11','GOUT2','GOUT3','GOUT4','GOUT5','GOUT6','GOUT7','GOUT8','GOUT9') ")->save(array('status'=>$status));
                break;
                //销售出库        
         case 'ShipmentXiaoshouM':
               $sqModel = M('ShipmentSq');
               $sqModel->where("ParentKey={$id} and s_type='SO' ")->save(array('status'=>$status));
               break;
            
        }
      
        return $m->where("U_wms_id='${id}'")->save(array('status'=>$status)); //主表记录状态
    }
    
   function updateItemCodebars($Codebars,$itemCode){
      $sql = " update oitm set codebars='{$Codebars}' where ItemCode='{$itemCode}'";
      return self::$sqlObj->saveBysql($sql);
   }
   
   /**
    * sap关闭采购入库单
    * @param unknown $docentry
    */
   static function colsereceipt($docentry){
       $smodel= M('ReceiptconfimS');
       $res = $smodel->where("BaseEntry = {$docentry}")->find();
       if(!$res) return false;
       $update = array('status'=>2);
       $u_wms_id = $res['ParentKey']; //主表u_wms_id
       $mmodel= M('ReceiptconfimM');
       $mmodel->where("U_wms_id = {$u_wms_id}")->save($update);
       $smodel->where("ParentKey = {$u_wms_id}")->save($update);
       $sqmodel= M('ReceiptconfimSq');
       $sqmodel->where("ParentKey = {$u_wms_id} and r_type='PO' ")->save($update);
       return true;
       
   }
   
   /**
    * wms 发货,同步到SAP
    * @param unknown $data
    */
   private  function shipmenttoSapDB($data=array()){
       $insertSqlPriex = "INSERT into Import_Z0090 (docentry,Lineid,orderid,Phone,ExpNo,ExpCom,Weight,SerNum) VALUES";
       
       if(strpos($data['SHIPMENT']['ShipmentId'], '~')){
           $orderID = explode('~',$data['SHIPMENT']['ShipmentId'])[0];
       }else  if(strpos($data['SHIPMENT']['ShipmentId'], '#')){
           $orderID = explode('#', $data['SHIPMENT']['ShipmentId'])[0];
       }  else{
           $orderID = explode('@', $data['SHIPMENT']['ShipmentId'])[0];
       }
       
       $expNo   =$data['SHIPMENT']['TrackingNumber'];
       $expCom  =$data['SHIPMENT']['Carrier'];
       $weight  =((int)$data['SHIPMENT']['Weight'])/1000;
       $sqlValue='';
       foreach ($data['SHIPMENT']['Items']['Item'] as $item){
           $doc = explode('-',$item['Erporderlinenum']);
           $serNum=$item['ManSernum']?:'';
           $sqlValue.="('{$doc[0]}','{$doc[1]}','{$orderID}','','{$expNo}','{$expCom}','{$weight}','{$serNum}'),";
           
       }
       $sqlValue=rtrim($sqlValue,',');
       return self::$sqlObj->saveBysql($insertSqlPriex.$sqlValue);
       
   }
    
    
}